package com.heima.media.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    @Override  //进入到Controller方法之前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("userId");
        String name = request.getHeader("name");
        if(StringUtils.isNotBlank(userId)){
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            user.setName(name);
//           把user 放到一个公共的位置
            UserThreadLocalUtil.setUser(user);
        }
        return true;
    }

    @Override  //从到Controller方法出来后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocalUtil.removeUser();
    }

}
